package com.module.aichat.ui.chatMain

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.common.base.app.viewmodel.BaseViewModel
import androidx.lifecycle.viewModelScope
import com.common.app.data.bean.KeyEvents
import com.common.base.app.extras.doOnIOThread
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.onCompletion
import com.module.aichat.data.AiChatApi
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.yes
import com.common.base.app.viewmodel.Cancel
import com.common.base.data.CommonBean
import com.common.base.utils.JsonUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.aichat.data.bean.FirmAIChatModel
import com.module.aichat.data.bean.MsgFeedbackModel
import com.module.aichat.data.protocol.messageContent.TextMessageContent
import com.module.aichat.db.table.DBMessage
import com.module.aichat.repo.ChatMessageRepo

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/06/25
 * <p>
 * 描述：
 * <p>
 * 修订历史：
 */
class ChatMainViewModel : BaseViewModel() {

    // 聊天消息列表状态
    val chatMessages = MutableLiveData<List<DBMessage>>()

    // 当前正在接收的消息索引
    private var currentReceiveMessageIndex: Int = -1
    // 问题首次回来
    private var questionFirstCallback = false

    var isSendState = false

    init {
        getDefData()
    }

    fun getDefData(){
        // 初始化一些测试数据
        val mData = mutableListOf<DBMessage>()

//        mData.add(DBMessage.obtainDBSendMessage(TextMessageContent.obtainTextMsgContent().apply { text = "vasvasvsdavadsv" }, "mConversationId",1))
//        mData.add(DBMessage.obtainDBReceiveMessage(TextMessageContent.obtainTextMsgContent().apply { text = "傻閪閪" }, "mAIId",1))
//        mData.add(DBMessage.obtainDBSendMessage(TextMessageContent.obtainTextMsgContent().apply { text = "天气如何？" }, "mConversationId",1))
//        mData.add(DBMessage.obtainDBReceiveMessage(TextMessageContent.obtainTextMsgContent().apply { text = "# 明天天气预报\n" +
//                " \n" +
//                "**日期**：2023年3月20日\n" +
//                " \n" +
//                "**天气状况**：晴朗\n" +
//                " \n" +
//                "![明天天气图标](http://gips3.baidu.com/it/u=2489404253,92500118&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280)\n" +
//                " \n" +
//                "**温度范围**：最低10°C，最高22°C\n" +
//                " \n" +
//                "**风向**：东南风，风力2级\n" +
//                " \n" +
//                "**湿度**：50%" }, "mAIId",1))

        ChatMessageRepo.instance.findAll()?.let {
//        ChatMessageRepo.instance.findAllByStatus(0)?.let {
            mData.addAll(it)
        }
        chatMessages.value = mData
    }

    /**
     * 发送文本消息
     */
    fun sendTextMessage(sendText: String,mId: Int = 0) {
        if (isSendState) return
        isSendState = true
        questionFirstCallback = false
        viewModelScope.launch {
            // 临时变量累加answer内容
            var accumulatedAnswer = ""
            try {
                // 1. 先添加用户发送的消息
                val userMessage = DBMessage.obtainDBSendMessage(TextMessageContent.obtainTextMsgContent().apply { text = sendText }, "mConversationId",1)
                addMessage(userMessage)

                // 2. 创建AI回复的空消息
                val aiMessage = DBMessage.obtainDBReceiveMessage(TextMessageContent.obtainTextMsgContent().apply { text = "" }, userMessage.id,0)
                addMessage(aiMessage)
                currentReceiveMessageIndex = (chatMessages.value?.size?:0) - 1

                // 3. 调用SSE接口获取流式响应
                AiChatApi.getSseFlow(sendText,mId)
                    .catch { exception ->
                        // 处理错误
                        Log.e("AIChat-SSE", "_sseData: 处理错误: exception")
                        updateReceiveMessage(mText ="发送失败：${exception.message}")
                        currentReceiveMessageIndex = -1
                        LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND_ERROR).post(this)
                        isSendState = false
                    }
                    .onCompletion {
                        // 流结束时的处理
                        currentReceiveMessageIndex = -1
                        Log.d("AIChat-SSE", "_sseData: 流结束时的处理: onCompletion")
                        LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND).post(this)
                    }
                    .collect { responseText ->
                        Log.d("AIChat-SSE", "_sseData: $responseText")
                        questionFirstCallback.no {
                            questionFirstCallback = true
                            Log.d("AIChat-SSE", "_sseData: KEY_AICHAT_ALLOW_SEND_END")
//                            LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND_END).post(this)
                        }
                        JsonUtils.fromJson(responseText, FirmAIChatModel::class.java)?.apply {
                            when(event){
                                "message"-> {
                                    Log.d("AIChat-SSE", "_sseData: _sseData-event:message")
                                    answer.isNullOrEmpty().no {
                                        // 累加answer内容
                                        accumulatedAnswer += answer?.replace("\\u", "\\\\u")
                                        // 更新UI显示
                                        updateReceiveMessage(mText =accumulatedAnswer, messageId = message_id?:"")
                                    }
                                }
                                "workflow_finished"->{
                                    Log.d("AIChat-SSE", "_sseData: _sseData-event:workflow_finished")
                                    //用data?.outputs?.answer数据和累加数据校验
                                    data?.outputs?.answer?.let { outputsAnswerIt->
                                        (outputsAnswerIt != accumulatedAnswer.trimEnd()).yes {
                                            updateReceiveMessage(mText =outputsAnswerIt, messageId = message_id?:"")
                                        }.otherwise {
                                            LiveEventBus.get(KeyEvents.KEY_AICHAT_RHV_ROLL_BOT).post(this)
                                        }
                                    }
//                                    LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND).post(this)
                                    isSendState = false
                                }
                            }

                        }
                    }

            } catch (e: Exception) {
                // 处理异常
                Log.e("AIChat-SSE", "_sseData: Exception")
                updateReceiveMessage(mText ="发送失败：${e.message}")
                LiveEventBus.get(KeyEvents.KEY_AICHAT_ALLOW_SEND_ERROR).post(this)
                isSendState = false
            }
        }
    }

    /**
     * 添加消息到列表
     */
    private fun addMessage(message: DBMessage) {
        ChatMessageRepo.instance.add2DB(message)//插入数据
        chatMessages.value?.let {
            val currentList = it.toMutableList()
            currentList.add(message)
            chatMessages.value = currentList
        }
    }

    /**
     * 追加文本到当前接收的消息
     */
    private fun appendToReceiveMessage(mText: String) {
        if (currentReceiveMessageIndex >= 0 && currentReceiveMessageIndex < (chatMessages.value?.size?:0)) {
            chatMessages.value?.let {
                val currentList = it.toMutableList()
                val currentMessage = currentList[currentReceiveMessageIndex]
                val curMsgContent = currentMessage.content as TextMessageContent
                currentMessage.content = TextMessageContent.obtainTextMsgContent().apply { text =  (curMsgContent.text ?: "") + mText }
                currentList[currentReceiveMessageIndex] = currentMessage
                chatMessages.value = currentList
            }
        }
    }

    /**
     * 更新当前接收消息的文本（用于错误处理）
     */
    private fun updateReceiveMessage(mText: String,taskId: String="",messageId: String="",conversationId: String="",) {
        if (currentReceiveMessageIndex >= 0 && currentReceiveMessageIndex < (chatMessages.value?.size?:0)) {
            chatMessages.value?.let {
                val currentList = it.toMutableList()
                chatMessages.value?.toMutableList()
                val currentMessage = currentList[currentReceiveMessageIndex]
                currentMessage.sendStatus = 1
                taskId.isNullOrEmpty().no { currentMessage.taskId = taskId }
                messageId.isNullOrEmpty().no { currentMessage.messageId = messageId }
                conversationId.isNullOrEmpty().no { currentMessage.conversationId = conversationId }
                currentMessage.content = TextMessageContent.obtainTextMsgContent().apply { text = mText }
                ChatMessageRepo.instance.add2DB(currentMessage)//插入数据
                currentList[currentReceiveMessageIndex] = currentMessage
                chatMessages.value = currentList
            }
        }
    }

    fun getSseFlow() = emit {
        // 保留原有方法
    }

    fun getProblemSuggestions(error: Cancel): LiveData<CommonBean<List<String>>> = emit(error) {
        AiChatApi.getProblemSuggestions()
    }

    fun requestMsgFeedback(msgId:String, rating:String, error: Cancel): LiveData<CommonBean<MsgFeedbackModel>> = emit(error) {
        AiChatApi.requestMsgFeedback(msgId,rating)
    }

    fun requestStopAiMsg(error: Cancel): LiveData<CommonBean<Any>> = emit(error) {
        AiChatApi.requestStopAiMsg()
    }

    fun deleteLastLoadingStatusData(){
//        val lastDataId = chatMessages.value?.lastOrNull()?.id
//        Log.d("SOSOU-ChatMainViewModel", "最后一条数据的id: $lastDataId")
        doOnIOThread {
            chatMessages.value?.lastOrNull()?.let {
                (it.sendStatus == 0).yes {
                    it.sendStatus = 2
                    ChatMessageRepo.instance.add2DB(it)//插入数据
                }
            }
        }

    }
}